﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using BattleShipPro.Ships;

namespace BattleShipPro
{
    /// <summary>
    /// Interaction logic for GameBoardControl.xaml
    /// </summary>
    public partial class GameBoardControl : UserControl
    {
        protected Session Session { get; set; }
        public GameBoardControl()
        {
            InitializeComponent();
            for (int i = 0; i < Constants.BoardSize; i++)
            {
                mainGrid.RowDefinitions.Add(new RowDefinition());
                mainGrid.ColumnDefinitions.Add(new ColumnDefinition());
            }
        }

        public void LoadGame(Session session)
        {
            Clear();

            Session = session;
            foreach (var battleShip in session.BattleShips)
            {
                var ship = GetShip(battleShip.Name);
                Grid.SetColumn(ship, battleShip.StartX);
                Grid.SetRow(ship, battleShip.StartY);
                switch (battleShip.Orientation)
                {
                    case Orientation.Horizontal:
                        Grid.SetColumnSpan(ship, battleShip.Spaces);
                        break;
                    case Orientation.Vertical:
                        Grid.SetRowSpan(ship, battleShip.Spaces);
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                mainGrid.Children.Add(ship);
            }
        }


        private FrameworkElement GetShip(string name)
        {
            switch (name)
            {
                case Constants.AircraftCarrier:
                    return new AircraftCarrier();
                case Constants.BattleShip:
                    return new BattleshipControl();
                case Constants.Destroyer:
                    return new Destroyer();
                case Constants.Submarine:
                    return new Submarine();
                case Constants.PatrolBoat:
                    return new PatrolBoat();
                default:
                    return null;
            }
        }

        public void ReceiveAttack(int x, int y)
        {
            var fire = new Fire();
            Grid.SetColumn(fire, x);
            Grid.SetRow(fire, y);
            mainGrid.Children.Add(fire);
        }

        public void Clear()
        {
            mainGrid.Children.Clear();
        }
    }
}
